package MailLogger;
import java.io.*;
import java.net.*;
import java.util.*;

public class MailSender {
  Socket conn;
  static final String EOL = "\r\n"; // network end of line
  String server, from;
    
  public MailSender(String server, String from){
    this.server = server;
    this.from = from;
  }
    
  public void sendMail(String recipient, String subject, String message) throws Exception{//throws ProtocolException{
    try{
      conn = new Socket(server, 25);
      
      InputStreamReader input = new InputStreamReader(conn.getInputStream());
      BufferedReader brIn = new BufferedReader(input);
      
      OutputStreamWriter output = new OutputStreamWriter(conn.getOutputStream());
      BufferedWriter brOut = new BufferedWriter(output);
          
      String returnMessage;
      String host= "";
      
      InetAddress local;
      try {
         local = InetAddress.getLocalHost();
         host = local.getHostName();
      }
      catch (UnknownHostException ioe) {}         
      writeMail(brOut, "HELO " + host + EOL);
      writeMail(brOut, "MAIL FROM: "+ from + EOL);
      writeMail(brOut, "RCPT TO: " + recipient +EOL);
      writeMail(brOut, "DATA" + EOL);
      writeMail(brOut, "Subject: "+ subject + EOL);
      writeMail(brOut, "From: " + from + EOL);

      writeMail(brOut, message);
      writeMail(brOut, EOL+"."+EOL);
      writeMail(brOut, "QUIT");
          
      brIn.readLine();
      //conn.close(); 
    }  
    catch(Exception e){
      e.printStackTrace();
      throw new Exception("send failed");
    }
    
  }
  
  private void writeMail(BufferedWriter brOut, String message) throws IOException{
    brOut.write(message);
    brOut.flush();
  }  

  public void close() throws IOException {
    conn.close(); 
  }
  
  public static void main(String[] args){
    MailSender ms = new MailSender("smtp.my.nthu.edu.tw", "g9662550@oz.nthu.edu.tw");
    try {
      ms.sendMail("chintown@gmail.com", "this is a test", "test");
      ms.close();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
